package com.azarias.model.pojo;

import lombok.extern.slf4j.Slf4j;

import java.util.UUID;

/**
 * @description: 微服务实例
 * @author: Azarias_Jx
 * @date: 2022/1/2 14:41
 */
@Slf4j
public class ServiceInstance {
    /**
     * 判断一个服务实例不再存活的周期
     */
    private static final Long NOT_ALIVE_PERIOD = 90 * 1000L;


    //服务id
    private String serviceInstanceId;
    //服务名称
    private String serviceName;
    //主机名称
    private String hostName;
    //服务ip
    private String ip;
    //服务端口
    private Integer port;

    /**
     * 契约
    */
    private Lease lease;

    public String getServiceInstanceId() {
        return serviceInstanceId;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Lease getLease() {
        return lease;
    }
    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }
    public ServiceInstance(){
        this.serviceInstanceId = UUID.randomUUID().toString().replace("-", "");
        this.lease = new Lease();
    }
    //契约续租
    public void renew(){
        this.lease.renew();
    }
    //契约续租
    public boolean isAlive(){
        return this.lease.isAlive();
    }


    /**
     * 契约
     * 维护了一个服务实例跟当前的这个注册中心之间的联系
     * 包括了心跳的时间，创建的时间，等等
     *
     */
    private class  Lease{
        private volatile  Long latestHeartbeatTime = 0L;

        public Lease() {
            this.latestHeartbeatTime = System.currentTimeMillis();
        }

        //契约续租
        public void renew(){
            latestHeartbeatTime = System.currentTimeMillis();
            log.debug("服务实例【" + serviceInstanceId + "】，进行续约：" + latestHeartbeatTime);
        }

        //判断契约是否还在存活
        //判断条件是上一次时间到现在的间隔
        public Boolean isAlive(){
            //如果时间间隔大于配置时间则 不在存活
            if(System.currentTimeMillis()-this.latestHeartbeatTime>=NOT_ALIVE_PERIOD){
                log.debug("服务实例【" + serviceInstanceId + "】，不再存活");
                return false;
            }
            log.debug("服务实例【" + serviceInstanceId + "】，还在");
            return true;
        }
    }

    @Override
    public String toString() {
        return "ServiceInstance{" +
                "serviceInstanceId='" + serviceInstanceId + '\'' +
                ", serviceName='" + serviceName + '\'' +
                ", hostName='" + hostName + '\'' +
                ", ip='" + ip + '\'' +
                ", port=" + port +
                ", lease=" + lease +
                '}';
    }
}
